package com.itheima.controller;

import com.fasterxml.jackson.databind.util.BeanUtil;
import com.itheima.bean.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
    private UserService service = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //设置请求和响应编码
            req.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html;charset=UTF-8");

            //1.获取请求参数
            Map<String, String[]> map = req.getParameterMap();
            //2.封装User对象
            User user = new User();
            BeanUtils.populate(user,map);

            //3.调用业务层的登录方法
            User existUser = service.login(user);

            //4.判断是否查询出结果
            if(existUser != null) {
                //将用户名存入会话域当中
                req.getSession().setAttribute("username",existUser.getUsername());
                //响应给客户端true
                resp.getWriter().write("true");
            }else {
                //响应给客户端false
                resp.getWriter().write("false");
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
